<?php

namespace SinoPHP\BbdBoss\Model;

use Upfor\UpforPHP\Model;

/**
 * Cache刷新系统所需关联关系
 */
class CacheSystemRelation extends Model {

    // 目前固定写死, 数据库不可删除
    public $subControlRoleId = 1;

    /**
     * 查询分控所属IP列表
     *
     * @param  integer $subControlRoleId
     * @return array
     */
    public function getSubControlServerIpList($subControlRoleId) {
        // 分控的服务器组
        $subControlGroupIds = $this->db->table('server_group')->where('server_role_id', $subControlRoleId)->column('server_group_id');
        if (empty($subControlGroupIds)) {
            return [];
        }

        // 分控关联的IP
        $ipIds = $this->getIpIdsByGroupId($subControlGroupIds);
        if (empty($ipIds)) {
            return [];
        }

        // IP信息列表
        // 每个机房确保只有一个分控
        $ipList = $this->db->table('server_ip')->field([
            'ip_id',
            'ip',
            'hostname',
            'server_area',
            'status',
        ])->where([
            'ip_id' => $ipIds,
            'status' => 1,
            'is_delete' => 0,
        ])->group('server_area')->getList();

        return $ipList;
    }

    /**
     * 根据绑定的服务器组IDs查询关联的IP列表
     *
     * @param  array $serverGroupIds
     * @return array
     */
    public function getIpIdsByGroupId($serverGroupIds) {
        return $this->db->table('server_group_ip')->where('server_group_id', $serverGroupIds)->column('ip_id');
    }

    public function getBindIpList(array $where) {
        return $this->db->table('server_ip')->where($where)->getList();
    }

    /**
     * 根据绑定的IP查询关联的服务器组IDs
     *
     * @param  array $ipIds
     * @return array
     */
    public function getRefGroupListByBindIp($ipIds) {
        $list = $this->db->table('server_group_ip')->where('ip_id', $ipIds)->getList();

        $refList = array();
        $bindGroupIds = array();
        foreach ($list as $row) {
            $refList[$row['ip_id']][$row['server_group_id']] = $row['server_group_id'];
            $bindGroupIds[] = $row['server_group_id'];
        }

        return [$refList, $bindGroupIds];
    }

    /**
     * 根据服务器组IDs查询关联的域名
     *
     * @param  array $groupIds
     * @return array
     */
    public function getDomainListByBindGroup($groupIds) {
        $list = $this->db->table('customer_domain_server_group', 'groupRef')->join('customer_domain', ['customer_domain.domain_id' => 'groupRef.domain_id'])->field(['customer_domain.domain_name', 'groupRef.server_group_id'])->where('groupRef.server_group_id', $groupIds)->getList();

        $refList = array();
        foreach ($list as $row) {
            if (!empty($row['domain_name'])) {
                $refList[$row['server_group_id']][] = $row['domain_name'];
            }
        }

        return $refList;
    }

    /**
     * 查询所有可用服务器组
     *
     * @return array
     */
    public function getAllServerGroupList() {
        return $this->db->table('server_group')->getList();
    }

}
